<?php
defined('_XR_EXEC') or die();
/**
 * test module
 */
class point_model extends model
{ 
	public function __construct() {
		parent::__construct();
	}
	/* 获取积分余额 */
  public function getbalance($user_id){
		$db = factory::getDBO();
		return $db->loadresult('select point from t_user where id="'.intval($user_id).'" ');
	}
	
	

	public function add_byslug($pointtype_slug,$user_id,$point,$remark='',$created_user_id='1',$created_ip='',$ifenough=true,$order_id=0){
		$pointtype_id = '0';
		$db = factory::getdbo();
		$pointtype_id = $db->loadresult('select id from `#__pointtype` where active=1 and slug="'.$pointtype_slug.'" ');
		if(!$pointtype_id){
			$this->setErrorNum('10');
			$this->setError('积分事务类别不存在，或事务未激活');
			return false;
		}
	//	debug::show($pointtype_id,$user_id,$point,$remark,$created_user_id,$created_ip,$ifenough,$order_id);
		return $this->add($pointtype_id,$user_id,$point,$remark,$created_user_id,$created_ip,$ifenough,$order_id);
	}	
	
	
	
	
	public function add($pointtype_id,$user_id,$point,$remark='',$created_user_id='1',$created_ip='',$ifenough=true,$order_id='0'){
		$db = factory::getDBO();
		$db->begin(); 
		$actions = $db->loadresult('select actions from `#__pointtype` where active=1 and id="'.intval($pointtype_id).'"  ');
		if($actions === false){
			$db->rollback();
			$this->setError('积分事务类别不存在，或事务未激活');
			return false;
		}
		if($actions == '-'){
			$point = abs($point) * -1;
		}else{
			$point = abs($point);
		}
		/* 余额判断 */
		if($ifenough === true){
			if($this->getbalance($user_id) + $point < 0 ){
				$db->rollback();
				$this->setError('会员账户积分不足');
				return false;
			}
		}	
	  # 更新余额
		if(!$db->query('update t_user set point=point+'.$point.' where id="'.$user_id.'"') ){
			$db->rollback();
			$this->setError('更新积分失败');
			return false;
		}
		/* 插入消费数据 */
		$point_id = $db->insert('point',array(
			'pointtype_id'=>$pointtype_id,
			'user_id'=>$user_id, 
			'point'=>($point*-1),
			'point_cur'=>$this->getbalance($user_id),
			'remark'=>$remark, 
			'created'=>'now()',
			'created_user_id'=>$created_user_id,
			'created_ip'=>$created_ip,
			'order_id'=>$order_id
		));
		//debug($user_id,$trans_id);
		if(!$point_id){
			$db->rollback();
			$this->setError('系统繁忙，请稍后重试');
			return false;
		}
		$db->commit();
		return $point_id;
	}
}

?>